package system.task.logger;

import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;

public class TaskLoggerWebSocketWriter implements TaskLoggerWriter {
    private final WebSocketSession webSocketSession;

    public TaskLoggerWebSocketWriter(WebSocketSession webSocketSession) {
        this.webSocketSession = webSocketSession;
    }

    @Override
    public void close() throws Exception {
        this.webSocketSession.close();
    }

    @Override
    public void info(String time, String message, boolean newLine) {
        try {
            if (this.webSocketSession.isOpen()) {
                StringBuilder builder = TaskLoggerUtil.buildContent(time, message, newLine);
                this.webSocketSession.sendMessage(new TextMessage(builder.toString()));
            }
        } catch (IOException e) {
            // ignore
        }
    }

    @Override
    public void error(String time, String message, boolean newLine) {
        try {
            if (this.webSocketSession.isOpen()) {
                StringBuilder builder = TaskLoggerUtil.buildError(time, message, newLine);
                this.webSocketSession.sendMessage(new TextMessage(builder.toString()));
            }
        } catch (IOException e) {
            // ignore
        }
    }
}
